package AddProduct;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class InsertIntoCategoryAndMaterial
 * This servlet insert data into ITEM_MATERIALS and ITEM_CATEGORIES tables in database.
 * @author desso
 */
@WebServlet("/InsertIntoCategoryAndMaterial")
public class InsertIntoCategoryAndMaterial extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public InsertIntoCategoryAndMaterial() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession sess = request.getSession();	
		
	    try {	   
	    	Connection databaseConnection = SQL.getConnection();		
			insertIntoItemCategories(request, sess, databaseConnection);
			insertIntoItemMaterials(request, sess, databaseConnection);	
			response.sendRedirect("ChooseSizeAndColor");			
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void insertIntoItemCategories(HttpServletRequest request, HttpSession sess, Connection dbConnection) throws SQLException {
		PreparedStatement prepareStatement = dbConnection.prepareStatement(SQLStatements.INSERT_INTO_ITEM_CATEGORIES_TABLE);
		prepareStatement.setLong(1, (Long) sess.getAttribute("item_id"));
		prepareStatement.setString(2, request.getParameter("category"));
		prepareStatement.executeUpdate();
	}

	private void insertIntoItemMaterials(HttpServletRequest request, HttpSession sess, Connection dbConnection) throws SQLException {
		PreparedStatement prepareStatement = dbConnection.prepareStatement(SQLStatements.INSERT_INTO_ITEM_MATERIALS_TABLE);	 
		prepareStatement.setLong(1,  (Long)sess.getAttribute("item_id"));
		prepareStatement.setString(2, request.getParameter("material"));
		prepareStatement.setString(3, request.getParameter("percentage"));
		prepareStatement.executeUpdate();
	}
}
